<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>活动考勤管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #4361ee;
            --success-color: #4cc9f0;
            --warning-color: #f72585;
            --danger-color: #e63946;
        }

        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .header {
            background: linear-gradient(135deg, var(--primary-color), #3a0ca3);
            color: white;
            padding: 1rem 0;
            margin-bottom: 2rem;
        }

        .card {
            border-radius: 15px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: none;
            margin-bottom: 1.5rem;
            transition: transform 0.3s ease;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card-header {
            background: transparent;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            font-weight: 600;
            padding: 1.25rem 1.5rem;
        }

        .status-badge {
            padding: 0.5em 0.75em;
            border-radius: 20px;
            font-size: 0.85em;
            font-weight: 500;
        }

        .status-present {
            background-color: #d4edda;
            color: #155724;
        }

        .status-absent {
            background-color: #f8d7da;
            color: #721c24;
        }

        .status-late {
            background-color: #fff3cd;
            color: #856404;
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .action-btn {
            margin: 0 2px;
        }

        .search-box {
            background: white;
            border-radius: 30px;
            padding: 0.5rem 1rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .table th {
            font-weight: 600;
        }

        .table-hover tbody tr:hover {
            background-color: rgba(67, 97, 238, 0.05);
        }

        .modal-content {
            border-radius: 15px;
            border: none;
        }

        .form-control, .form-select {
            border-radius: 10px;
            padding: 0.75rem;
        }

        .toast-container {
            z-index: 1050;
        }
    </style>
</head>
<body>
<!-- 头部 -->
<div class="header text-center">
    <div class="container">
        <h1><i class="bi bi-calendar-check"></i> 活动考勤管理</h1>
        <p class="lead">管理志愿者活动考勤信息</p>
    </div>
</div>

<div class="container">
    <!-- 操作区域 -->
    <div class="row mb-4">
        <div class="col-md-8">
            <div class="search-box d-flex align-items-center">
                <i class="bi bi-search me-2 text-muted"></i>
                <input type="text" class="form-control border-0" placeholder="搜索考勤记录..." id="searchInput">
            </div>
        </div>
        <div class="col-md-4 text-end">
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#attendanceModal">
                <i class="bi bi-plus-circle"></i> 新增考勤
            </button>
        </div>
    </div>

    <!-- 考勤统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-muted">总记录数</h5>
                    <h2 class="text-primary" id="totalRecords">0</h2>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-muted">已签到</h5>
                    <h2 class="text-success" id="signedIn">0</h2>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-muted">未签退</h5>
                    <h2 class="text-warning" id="notSignedOut">0</h2>
                </div>
            </div>
        </div>
    </div>

    <!-- 考勤列表 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="bi bi-list-check"></i> 考勤记录列表</span>
            <div>
                <select class="form-select form-select-sm d-inline-block w-auto" id="statusFilter">
                    <option value="">全部状态</option>
                    <option value="1">已签到</option>
                    <option value="2">已签退</option>
                    <option value="0">未签到</option>
                </select>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>考勤ID</th>
                        <th>活动ID</th>
                        <th>用户ID</th>
                        <th>签到时间</th>
                        <th>签退时间</th>
                        <th>考勤状态</th>
                        <th>服务时长(小时)</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="attendanceTableBody">
                    <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center" id="pagination">
                    <li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>
                    <li class="page-item active"><a class="page-link" href="#">1</a></li>
                    <li class="page-item"><a class="page-link" href="#">下一页</a></li>
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- 新增/编辑考勤模态框 -->
<div class="modal fade" id="attendanceModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="attendanceModalLabel"><i class="bi bi-calendar-plus"></i> 考勤信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="attendanceForm">
                    <input type="hidden" id="attendance_id">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="activity_id" class="form-label">活动ID</label>
                            <input type="number" class="form-control" id="activity_id" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="user_id" class="form-label">用户ID</label>
                            <input type="number" class="form-control" id="user_id" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="sign_in_time" class="form-label">签到时间</label>
                            <input type="datetime-local" class="form-control" id="sign_in_time">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="sign_out_time" class="form-label">签退时间</label>
                            <input type="datetime-local" class="form-control" id="sign_out_time">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="attendance_status" class="form-label">考勤状态</label>
                            <select class="form-select" id="attendance_status" required>
                                <option value="0">未签到</option>
                                <option value="1">已签到</option>
                                <option value="2">已签退</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="hours" class="form-label">服务时长(小时)</label>
                            <input type="number" step="0.1" class="form-control" id="hours">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveAttendanceBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- Toast提示 -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="toast" class="toast" role="alert">
        <div class="toast-header">
            <strong class="me-auto">提示</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body" id="toastMessage"></div>
    </div>
</div>

<!-- JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script>
    // API基础URL - 这里假设你的后端接口地址为 /api/attendance
    const API_BASE = 'http://localhost:8181/api/attendance';

    // 状态映射
    const statusMap = {
        0: { text: '未签到', class: 'status-absent' },
        1: { text: '已签到', class: 'status-present' },
        2: { text: '已签退', class: 'status-present' }
    };

    // 初始化页面
    document.addEventListener('DOMContentLoaded', function() {
        loadAttendanceData();

        // 绑定事件
        document.getElementById('saveAttendanceBtn').addEventListener('click', saveAttendance);
        document.getElementById('statusFilter').addEventListener('change', loadAttendanceData);
        document.getElementById('searchInput').addEventListener('input', loadAttendanceData);
    });

    // 加载考勤数据
    function loadAttendanceData() {
        axios.get(API_BASE)
            .then(response => {
                renderAttendanceTable(response.data);
                updateStatistics(response.data);
            })
            .catch(error => {
                console.error('加载数据出错:', error);
                showToast('加载数据出错', 'error');
            });
    }

    // 渲染考勤表格
    function renderAttendanceTable(attendances) {
        const tbody = document.getElementById('attendanceTableBody');
        tbody.innerHTML = '';

        if (!attendances || attendances.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" class="text-center">暂无数据</td></tr>';
            return;
        }

        attendances.forEach(attendance => {
            const statusInfo = statusMap[attendance.attendance_status] || { text: '未知', class: '' };
            const row = document.createElement('tr');

            row.innerHTML = `
                    <td>${attendance.attendance_id || '-'}</td>
                    <td>${attendance.activity_id || '-'}</td>
                    <td>${attendance.user_id || '-'}</td>
                    <td>${formatDateTime(attendance.sign_in_time) || '-'}</td>
                    <td>${formatDateTime(attendance.sign_out_time) || '-'}</td>
                    <td><span class="status-badge ${statusInfo.class}">${statusInfo.text}</span></td>
                    <td>${attendance.hours || '0'}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary action-btn" onclick="editAttendance(${attendance.attendance_id})">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger action-btn" onclick="deleteAttendance(${attendance.attendance_id})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                `;

            tbody.appendChild(row);
        });
    }

    // 更新统计数据
    function updateStatistics(attendances) {
        document.getElementById('totalRecords').textContent = attendances.length;

        let signedIn = 0;
        let notSignedOut = 0;

        attendances.forEach(attendance => {
            if (attendance.attendance_status >= 1) signedIn++;
            if (attendance.attendance_status == 1) notSignedOut++;
        });

        document.getElementById('signedIn').textContent = signedIn;
        document.getElementById('notSignedOut').textContent = notSignedOut;
    }

    // 格式化日期时间
    function formatDateTime(dateTimeString) {
        if (!dateTimeString) return '';
        const date = new Date(dateTimeString);
        return date.toLocaleString('zh-CN');
    }

    // 编辑考勤
    function editAttendance(id) {
        axios.get(`${API_BASE}/${id}`)
            .then(response => {
                const attendance = response.data;
                document.getElementById('attendance_id').value = attendance.attendance_id;
                document.getElementById('activity_id').value = attendance.activity_id;
                document.getElementById('user_id').value = attendance.user_id;
                document.getElementById('sign_in_time').value = formatDateTimeForInput(attendance.sign_in_time);
                document.getElementById('sign_out_time').value = formatDateTimeForInput(attendance.sign_out_time);
                document.getElementById('attendance_status').value = attendance.attendance_status;
                document.getElementById('hours').value = attendance.hours || '';

                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('attendanceModal'));
                modal.show();
            })
            .catch(error => {
                console.error('获取考勤信息出错:', error);
                showToast('获取考勤信息出错', 'error');
            });
    }

    // 保存考勤
    function saveAttendance() {
        const attendance = {
            activity_id: parseInt(document.getElementById('activity_id').value),
            user_id: BigInt(document.getElementById('user_id').value),
            sign_in_time: document.getElementById('sign_in_time').value ?
                new Date(document.getElementById('sign_in_time').value).toISOString() : null,
            sign_out_time: document.getElementById('sign_out_time').value ?
                new Date(document.getElementById('sign_out_time').value).toISOString() : null,
            attendance_status: parseInt(document.getElementById('attendance_status').value),
            hours: parseFloat(document.getElementById('hours').value) || null
        };

        const attendanceId = document.getElementById('attendance_id').value;
        const isUpdate = attendanceId !== '';

        const method = isUpdate ? 'put' : 'post';
        const url = isUpdate ? `${API_BASE}/${attendanceId}` : API_BASE;

        axios({
            method: method,
            url: url,
            data: attendance
        })
            .then(response => {
                showToast(isUpdate ? '更新成功' : '添加成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('attendanceModal')).hide();
                loadAttendanceData();
            })
            .catch(error => {
                console.error('保存出错:', error);
                showToast('保存出错', 'error');
            });
    }

    // 删除考勤
    function deleteAttendance(id) {
        if (!confirm('确定要删除这条考勤记录吗？')) {
            return;
        }

        axios.delete(`${API_BASE}/${id}`)
            .then(response => {
                showToast('删除成功', 'success');
                loadAttendanceData();
            })
            .catch(error => {
                console.error('删除出错:', error);
                showToast('删除出错', 'error');
            });
    }

    // 格式化日期时间用于输入框
    function formatDateTimeForInput(dateTimeString) {
        if (!dateTimeString) return '';
        const date = new Date(dateTimeString);
        return date.toISOString().slice(0, 16);
    }

    // 显示Toast提示
    function showToast(message, type) {
        const toastEl = document.getElementById('toast');
        const toastMessageEl = document.getElementById('toastMessage');

        toastMessageEl.textContent = message;
        toastEl.classList.remove('text-bg-success', 'text-bg-danger');

        if (type === 'success') {
            toastEl.classList.add('text-bg-success');
        } else {
            toastEl.classList.add('text-bg-danger');
        }

        const toast = new bootstrap.Toast(toastEl);
        toast.show();
    }

    // 清空表单
    document.getElementById('attendanceModal').addEventListener('hidden.bs.modal', function () {
        document.getElementById('attendanceForm').reset();
        document.getElementById('attendance_id').value = '';
    });
</script>
</body>
</html>
